<?php
/**
 * The Action class
 */
abstract class Action
{
	private $_constructed = false;

	/**
	 * The validated input data
	 *
	 * @var array
	 */
	protected $_validatedInput;

	/**
	 * The URI array, contains: module, action, query array
	 *
	 * @var array
	 */
	public $uri;
	
	/**
	 * The view object
	 * 
	 * @var object
	 */
	public $view;

	/**
	 * Validate the data from client
	 * @return array
	 */
	protected function _validateInput()
	{
		$dtds = isset(Config::$array['dtd'][$this->uri['module']][$this->uri['action']]) ? Config::$array['dtd'][$this->uri['module']][$this->uri['action']] : array();
		if (0 < count($dtds))
		{
			foreach ($dtds as $variable => $dtd)
			{
				if (!isset($dtd['from']))
				{
					$dtd['from'] = 'request';
				}
				$validateCondition[$variable] = array('value' => Input::$dtd['from']($variable), 'dtd' => $dtd);
			}
			return $validateResult = Validator::Validate($validateCondition, $this->_validatedInput);
		}
	}

	/**
	 * The constructor function, initialize the URI property
	 */
	public function __construct()
	{
		if (isset($_SERVER['SERVER_PROTOCOL']))
		{
			$webRoot = substr($_SERVER['SCRIPT_FILENAME'], strlen(realpath($_SERVER['DOCUMENT_ROOT'])));
			if ('on' == Config::$array['route']['rewrite'])
			{
				$webRoot = substr($webRoot, 0, strrpos($webRoot, '/') + 1);
			}
			$uri['protocol'] = isset($_SERVER['HTTPS']) && 'on' == $_SERVER['HTTPS'] ? 'https' : 'http';
			$uri['port'] = '80' == $_SERVER['SERVER_PORT'] && 'http' == $uri['protocol'] || '443' == $_SERVER['SERVER_PORT'] && 'https' == $uri['protocol'] ? '' : ':' . $_SERVER['SERVER_PORT'];
			$uri['host'] = $_SERVER['SERVER_NAME'];
			$uri['base'] = sprintf('%s://%s%s%s', $uri['protocol'], $uri['host'], $uri['port'], $webRoot);
			$this->uri = $uri;
		}
		$this->_constructed = true;
	}

	/**
	 * Do something after subClass::__construct().
	 */
	public final function afterConstruct()
	{
		if (null === $this->view)
		{
			$this->view = new View();
		}
		$this->view->afterConstruct();
		if (!$this->_constructed)
		{
			DebugHelper::debug('SUBCLASS_NOT_CALL_PARENT_CONSTRUCTOR', array('calss' => get_class($this)));
		}
	}
}
